package 
{
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;

	/**
	 * 用于显示对象的对象类池
	 */	
	public class ObjectPool
	{
		private static var instance:ObjectPool;
		
		/**
		 * 作为对象池的词典dict 
		 */		
		private var objPoolDict:Dictionary = new Dictionary();
		
		public function ObjectPool()
		{
		}
		
		public static function getInstance():ObjectPool
		{
			if(instance == null)
			{
				instance = new ObjectPool;
			}
			
			return instance;
		}
		
		/**
		 * 向对象池中放入对象，以便重复利用 
		 * @param oldObj 要的放入对象
		 * 
		 */		
		public function push(oldObj:Object):void
		{
			var objName:String = getQualifiedClassName(oldObj);
			
			if(oldObj == null)
				return;
			
			if(this.objPoolDict[objName] == null)
			{
				this.objPoolDict[objName] = [];
			}
			
			this.objPoolDict[objName].push(oldObj);
		}
		
		/**
		 * 从对象池中取出需要的对象 
		 * @param targetObj 需要的对象类类名，没必要必须是类实例名，类型也可以
		 * @return 取出的相应对象
		 * 
		 */		
		public function pop(targetObj:Object):Object
		{
			var objName:String = getQualifiedClassName(targetObj);
			
			if(this.objPoolDict[objName] != null &&
				this.objPoolDict[objName].length > 0)
			{
				return this.objPoolDict[objName].pop() as Object;
			}
			
			var objClass:Class = getDefinitionByName(objName) as Class;
			
			var obj:Object = new objClass as Object;
			
			return obj;
		}
	}
}